/**
 * User: yeqingzhou01
 * Date: 14-3-6
 * Time: 下午8:19
 */
//var jot = require('json-over-tcp');
var net = require('net');
var JsonSocket = require('json-socket');
var dgram = require('dgram');
//
exports.JsonOverTcpServer = function (port, onReceived) {
    var server = net.createServer();
    server.listen(port);
    console.log('TCP listening port ' + port);
    server.on('connection', function (socket) { //This is a standard net.Socket
        socket.setEncoding('utf8');
        socket = new JsonSocket(socket); //Now we've decorated the net.Socket to be a JsonSocket
        socket.on('data', function (message) {
            onReceived(message);
            socket.sendMessage({received: message});
        });
        socket.on('error', function (message) {
            console.log("TCP Error: ");
            console.log(message);
            socket.sendEndMessage({endMsg: 'END'});
        });
    });
}
exports.JsonOverUdpServer = function(port, onReceived){
    var udpServer = dgram.createSocket('udp4');
    udpServer.on('listening', function () {
        var address = udpServer.address();
        console.log('UDP Server listening on ' + address.address + ":" + address.port);
    });
    udpServer.on('message', function (message, remote) {
        onReceived(message);
    });
    udpServer.bind(port, 'qd01-infop-saturn00.qd01.baidu.com');
}